package com.unis.service.znzf.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.unis.common.enums.QqlxEnum;
import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.TemplateUtil;
import com.unis.common.util.TimeUtil;
import com.unis.dto.ResultDto;
import com.unis.model.fzzx.Jjd;
import com.unis.model.znzf.Jlt;
import com.unis.model.znzf.ZnzfQueue;
import com.unis.pojo.znzf.ReqModel;
import com.unis.service.fzzx.JjdService;
import com.unis.service.system.CodeService;
import com.unis.service.znzf.JltService;
import com.unis.service.znzf.ZnzfQueueService;
import com.unis.service.znzf.ZnzfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.service.impl.BaseServiceImpl;
import com.unis.mapper.znzf.SfZfQqMapper;
import com.unis.model.znzf.SfZfQq;
import com.unis.service.znzf.SfZfQqService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see SfZfQqService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2019-02-28
 */
@Service("sfZfQqService")
public class SfZfQqServiceImpl extends BaseServiceImpl implements SfZfQqService {
	private static final Logger logger = LoggerFactory.getLogger(SfZfQqServiceImpl.class);
    @Autowired
    private SfZfQqMapper sfZfQqMapper;
	@Autowired
	private ZnzfQueueService znzfQueueService;
	@Autowired
	private ZnzfService znzfService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private JltService jltService;
	@Autowired
	private JjdService jjdService;
    /**
     * @see SfZfQqService#insert(SfZfQq sfZfQq)
     */
    @Override
    public int insert(SfZfQq sfZfQq) throws Exception {
    	if (sfZfQq!=null){
	        //sfZfQq.setPk(TemplateUtil.genUUID());
	        //menu.setPk(getPk("seqName","jgdm","A"));
	                
	        return sfZfQqMapper.insertSelective(sfZfQq);
    	}else{
    		logger.error("SfZfQqServiceImpl.insert时sfZfQq数据为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.insert时sfZfQq数据为空。");
    	}        
    }

	@Override
	public int insertSfZf(ReqModel reqModel) throws Exception {
		int resultNumber = 0;
		Map bean =  null;
		if(reqModel!=null && reqModel.getBean()!=null && !reqModel.getBean().isEmpty() && reqModel.getBean().size()>0){
			List<Map> list = new ArrayList<>();
			UserInfo user = this.getUserInfo();
			Map<String,String> mongoMap = new HashMap();
			Map<String, Map<String, String>> dicMap = codeService.queryDicWithSpecCode("010107");
			Date nowDate = this.getDbDate();

			Jjd jjd = jjdService.queryJjdByPrimaryKey(reqModel.getJjdPk());

			for (Map<String,String> map : reqModel.getBean()){
				if (map==null || map.isEmpty() || map.size()<1 ){
					continue;
				}
				bean = new HashMap();

				bean.put("shr",jjd!=null&&StringUtils.isNotBlank(jjd.getBarxm())?jjd.getBarxm():reqModel.getShr());

				bean.put("pk", TemplateUtil.genUUID());
				bean.put("lrdwdm",user.getJgdm());
				bean.put("lrdwmc",user.getJgmc());
				bean.put("lrrxm",user.getXm());
				bean.put("lrrjh",user.getJh());
				bean.put("jjdpk",reqModel.getJjdPk());
				bean.put("reason",reqModel.getSy());
				bean.put("subjecttype",StringUtils.isNotBlank(map.get("subjecttype"))?Short.parseShort(map.get("subjecttype")):1);

				bean.put("paycode",map.get("paycode"));
				bean.put("payname",map.get("payname"));

				String zh = StringUtils.isNotBlank(map.get("accnumber"))?map.get("accnumber"):"";
				bean.put("accnumber",zh);

				bean.put("transferamount",StringUtils.isNotBlank(map.get("transferamount"))?Integer.parseInt(map.get("transferamount")) : null);

				bean.put("starttime",nowDate);
				bean.put("expiretime",TimeUtil.addDay(nowDate,2));

				//报文生成所需参数
				bean.put("bankcode",map.get("paycode"));
				bean.put("bankname",map.get("payname"));
				bean.put("cardnumber",zh);
				bean.put("ajlb", dicMap.get("010107").get(reqModel.getAjlb()));
				bean.put("zzfs", map.get("zzfs"));
				bean.put("zzje",StringUtils.isNotBlank(map.get("transferamount"))?map.get("transferamount")+"" : "0");
				//bean.put("zzsj",StringUtils.isNotBlank(reqModel.getJjsj())?TimeUtil.fmtDate(TimeUtil.strToDate(reqModel.getJjsj(),"yyyyMMddHHmmss"),null) : null);
				bean.put("zzsj", reqModel.getJjsj());
				bean.put("accountname",reqModel.getShr());

				String mongoPk = "";
				if (mongoMap!=null && !mongoMap.isEmpty() && mongoMap.size()>0 && StringUtils.isNotBlank(mongoMap.get(zh))){
					mongoPk = mongoMap.get(zh);
				}else{
					Example example = new Example(SfZfQq.class);
					example.setOrderByClause("rksj DESC,pk asc");//设置排序
					Example.Criteria criteria = example.createCriteria();
					criteria.andEqualTo("yxx",1);
					criteria.andEqualTo("jjdpk",reqModel.getJjdPk());
					criteria.andEqualTo("lrdwdm",user.getJgdm());
					criteria.andEqualTo("paycode",bean.get("paycode"));
					criteria.andEqualTo("accnumber",bean.get("accnumber"));
					List<SfZfQq> qqList = this.queryListByExample(example);
					if (qqList!=null && !qqList.isEmpty() && qqList.size()>0){
						mongoPk = qqList.get(0).getFlws();
					}else{
						mongoPk = znzfService.insertMongo("sf","zf",bean);
					}
					mongoMap.put(zh,mongoPk);
				}
				bean.put("flws",mongoPk);
				/*bean.put("nlevel",reqModel.getNlevel());
				bean.put("sertype",new Short("2"));
				bean.put("parentpk",reqModel.getParentpk());
				bean.put("parentzh",reqModel.getParentzh());*/
				//jltService.checkJltAndInsert(bean);

				list.add(bean);
			}

			if (list!=null && !list.isEmpty() && list.size()>0){
				resultNumber = sfZfQqMapper.insertBatch(list);
				znzfQueueService.insertBatch(list, QqlxEnum.sfQqlxZhifu.getKey(),(short)1);
				for (Map map : list){
					//修改资金流中zfpk
					Jlt updJlt = new Jlt();
					updJlt.setPk(reqModel.getJltpk());
					updJlt.setZfpk((String)map.get("pk"));
					jltService.updateByPrimaryKey(updJlt);
				}
			}
		}
		return resultNumber;
	}

	/**
     * @see SfZfQqService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("SfZfQqServiceImpl.delete时pk为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.delete时pk为空。");
    	}else{
    		return sfZfQqMapper.deleteByPrimaryKey(pk);
    	}
    }

    /**
     * @see SfZfQqService#updateByPrimaryKey(SfZfQq sfZfQq)
     */
    @Override
    public int updateByPrimaryKey(SfZfQq sfZfQq) throws Exception {
        if (sfZfQq!=null){
        	if(StringUtils.isBlank(sfZfQq.getPk())){
        		logger.error("SfZfQqServiceImpl.updateByPrimaryKey时sfZfQq.Pk为空。");
        		throw new AppRuntimeException("SfZfQqServiceImpl.updateByPrimaryKey时sfZfQq.Pk为空。");
        	}
	        return sfZfQqMapper.updateByPrimaryKeySelective(sfZfQq);
    	}else{
    		logger.error("SfZfQqServiceImpl.updateByPrimaryKey时sfZfQq数据为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.updateByPrimaryKey时sfZfQq数据为空。");
    	}
    }
    /**
     * @see SfZfQqService#querySfZfQqByPrimaryKey(String pk)
     */
    @Override
    public SfZfQq querySfZfQqByPrimaryKey(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("SfZfQqServiceImpl.querySfZfQqByPrimaryKey时pk为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.querySfZfQqByPrimaryKey时pk为空。");
    	}else{
    		return sfZfQqMapper.selectByPrimaryKey(pk);
    	}
    }
    
    
    /**
     * @see SfZfQqService#queryAsObject(SfZfQq sfZfQq)
     */
    @Override
    public SfZfQq queryAsObject(SfZfQq sfZfQq) throws Exception {
        if (sfZfQq!=null){
	        return sfZfQqMapper.selectOne(sfZfQq);
    	}else{
    		logger.error("SfZfQqServiceImpl.queryAsObject时sfZfQq数据为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.queryAsObject时sfZfQq数据为空。");
    	}
    }
    
    /**
     * @see SfZfQqService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
    	if(example!=null){
    		return sfZfQqMapper.selectCountByExample(example);
    	}else{
    		logger.error("SfZfQqServiceImpl.queryCountByExample时example数据为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.queryCountByExample时example数据为空。");
    	}
    }
    /**
     * @see SfZfQqService#queryListByExample(Example example)
     */
    @Override
    public List<SfZfQq> queryListByExample(Example example) throws Exception {
    	if(example!=null){
    		return sfZfQqMapper.selectByExample(example);
    	}else{
    		logger.error("SfZfQqServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.queryListByExample时example数据为空。");
    	}
    }
    /**
     * @see SfZfQqService#queryPageInfoByExample(Example example,int pageNum,int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example,int pageNum,int pageSize) throws Exception {    	
    	if(example!=null){
    		PageHelper.startPage(pageNum,pageSize);
    		return new PageInfo(sfZfQqMapper.selectByExample(example));
    	}else{
    		logger.error("SfZfQqServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("SfZfQqServiceImpl.queryListByExample时example数据为空。");
    	}    	
    }
	/**
     * @see SfZfQqService#queryListByPage(Map parmMap,int pageNum,int pageSize)
     */
    @Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws  Exception{
    	if (parmMap!=null){
    		Example example = new Example(SfZfQq.class);
    		//example.setOrderByClause("rksj DESC,pk asc");设置排序
    		Example.Criteria criteria = example.createCriteria();
    		//criteria设置
    		// = --> andEqualTo(field,value)
    		// like --> andLike(field,likeValue)；likeValue 包含‘%’
    		// is null --> andIsNull(field)
    		// is not null --> andIsNotNull(field)
    		// <> --> andNotEqualTo(field)
    		// > --> andGreaterThan(field,value)
    		// >= --> andGreaterThanOrEqualTo(field,value)
    		// < --> andLessThan(field,value)
    		// <= --> andLessThanOrEqualTo(field,value)
    		// in --> andIn(field,Iterable value)
    		// not in --> andNotIn(field,Iterable value)
    		// between --> andBetween(field,beginValue,endValue)
    		// not like --> andNotLike(field,likeValue)；likeValue 包含‘%’
    		
    		// or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)
    		
    		//criteria.andEqualTo("yxx",1);设置yxx=1
    		/**
    		 *此方法请根据需要修改下方条件
    		*/
    		//此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
    		//生成条件中均为 and field = value 
    		//生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改
    		
    		boolean flag = false;
    		if(parmMap.get("pk")!=null && StringUtils.isNotBlank(parmMap.get("pk").toString())){
				criteria.andEqualTo("pk",parmMap.get("pk").toString().trim());
				flag = true;
			}
    		if(parmMap.get("jjdpk")!=null && StringUtils.isNotBlank(parmMap.get("jjdpk").toString())){
				criteria.andEqualTo("jjdpk",parmMap.get("jjdpk").toString().trim());
				flag = true;
			}
    		if(parmMap.get("applicationid")!=null && StringUtils.isNotBlank(parmMap.get("applicationid").toString())){
				criteria.andEqualTo("applicationid",parmMap.get("applicationid").toString().trim());
				flag = true;
			}
    		if(parmMap.get("subjecttype")!=null && StringUtils.isNotBlank(parmMap.get("subjecttype").toString())){
				criteria.andEqualTo("subjecttype",parmMap.get("subjecttype").toString().trim());
				flag = true;
			}
    		if(parmMap.get("paycode")!=null && StringUtils.isNotBlank(parmMap.get("paycode").toString())){
				criteria.andEqualTo("paycode",parmMap.get("paycode").toString().trim());
				flag = true;
			}
    		if(parmMap.get("payname")!=null && StringUtils.isNotBlank(parmMap.get("payname").toString())){
				criteria.andEqualTo("payname",parmMap.get("payname").toString().trim());
				flag = true;
			}
    		if(parmMap.get("accnumber")!=null && StringUtils.isNotBlank(parmMap.get("accnumber").toString())){
				criteria.andEqualTo("accnumber",parmMap.get("accnumber").toString().trim());
				flag = true;
			}
    		if(parmMap.get("transfertime")!=null && StringUtils.isNotBlank(parmMap.get("transfertime").toString())){
				criteria.andEqualTo("transfertime",parmMap.get("transfertime").toString().trim());
				flag = true;
			}
    		if(parmMap.get("transferamount")!=null && StringUtils.isNotBlank(parmMap.get("transferamount").toString())){
				criteria.andEqualTo("transferamount",parmMap.get("transferamount").toString().trim());
				flag = true;
			}
    		if(parmMap.get("reason")!=null && StringUtils.isNotBlank(parmMap.get("reason").toString())){
				criteria.andEqualTo("reason",parmMap.get("reason").toString().trim());
				flag = true;
			}
    		if(parmMap.get("remark")!=null && StringUtils.isNotBlank(parmMap.get("remark").toString())){
				criteria.andEqualTo("remark",parmMap.get("remark").toString().trim());
				flag = true;
			}
    		if(parmMap.get("starttime")!=null && StringUtils.isNotBlank(parmMap.get("starttime").toString())){
				criteria.andEqualTo("starttime",parmMap.get("starttime").toString().trim());
				flag = true;
			}
    		if(parmMap.get("expiretime")!=null && StringUtils.isNotBlank(parmMap.get("expiretime").toString())){
				criteria.andEqualTo("expiretime",parmMap.get("expiretime").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrdwdm")!=null && StringUtils.isNotBlank(parmMap.get("lrdwdm").toString())){
				criteria.andEqualTo("lrdwdm",parmMap.get("lrdwdm").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrdwmc")!=null && StringUtils.isNotBlank(parmMap.get("lrdwmc").toString())){
				criteria.andEqualTo("lrdwmc",parmMap.get("lrdwmc").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrrxm")!=null && StringUtils.isNotBlank(parmMap.get("lrrxm").toString())){
				criteria.andEqualTo("lrrxm",parmMap.get("lrrxm").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrrjh")!=null && StringUtils.isNotBlank(parmMap.get("lrrjh").toString())){
				criteria.andEqualTo("lrrjh",parmMap.get("lrrjh").toString().trim());
				flag = true;
			}
    		if(parmMap.get("rksj")!=null && StringUtils.isNotBlank(parmMap.get("rksj").toString())){
				criteria.andEqualTo("rksj",parmMap.get("rksj").toString().trim());
				flag = true;
			}
    		if(parmMap.get("yxx")!=null && StringUtils.isNotBlank(parmMap.get("yxx").toString())){
				criteria.andEqualTo("yxx",parmMap.get("yxx").toString().trim());
				flag = true;
			}
    		if(parmMap.get("reqflag")!=null && StringUtils.isNotBlank(parmMap.get("reqflag").toString())){
				criteria.andEqualTo("reqflag",parmMap.get("reqflag").toString().trim());
				flag = true;
			}
    		if(parmMap.get("reqdate")!=null && StringUtils.isNotBlank(parmMap.get("reqdate").toString())){
				criteria.andEqualTo("reqdate",parmMap.get("reqdate").toString().trim());
				flag = true;
			}
    		if(parmMap.get("reqcount")!=null && StringUtils.isNotBlank(parmMap.get("reqcount").toString())){
				criteria.andEqualTo("reqcount",parmMap.get("reqcount").toString().trim());
				flag = true;
			}
    		if(parmMap.get("resflag")!=null && StringUtils.isNotBlank(parmMap.get("resflag").toString())){
				criteria.andEqualTo("resflag",parmMap.get("resflag").toString().trim());
				flag = true;
			}
    		if(parmMap.get("resdate")!=null && StringUtils.isNotBlank(parmMap.get("resdate").toString())){
				criteria.andEqualTo("resdate",parmMap.get("resdate").toString().trim());
				flag = true;
			}
    		if(parmMap.get("resultcode")!=null && StringUtils.isNotBlank(parmMap.get("resultcode").toString())){
				criteria.andEqualTo("resultcode",parmMap.get("resultcode").toString().trim());
				flag = true;
			}
    		if(parmMap.get("feedbackremark")!=null && StringUtils.isNotBlank(parmMap.get("feedbackremark").toString())){
				criteria.andEqualTo("feedbackremark",parmMap.get("feedbackremark").toString().trim());
				flag = true;
			}
    		if(parmMap.get("flws")!=null && StringUtils.isNotBlank(parmMap.get("flws").toString())){
				criteria.andEqualTo("flws",parmMap.get("flws").toString().trim());
				flag = true;
			}
    		//一个条件都没有的时候给一个默认条件
    		if(!flag){
    		
    		}
    		PageInfo pageInfo = this.queryPageInfoByExample(example,pageNum,pageSize);
			ResultDto result = new ResultDto();
			result.setRows(pageInfo.getList());
			result.setPage(pageInfo.getPageNum());
			//result.setTotal(pageInfo.getPages());
			result.setTotal((int)pageInfo.getTotal());
			return result;
    	}else{
			logger.error("SfZfQqServiceImpl.queryListByPage时parmMap数据为空。");
			throw new AppRuntimeException("SfZfQqServiceImpl.queryListByPage时parmMap数据为空。");
		}
    }

	@Override
	public String insertSfZf(Jlt jlt) throws Exception {
		String result = null;
		UserInfo user = this.getUserInfo();
		Date nowDate = this.getDbDate();
		Map bean = new HashMap();

		Jjd jjd = jjdService.queryJjdByPrimaryKey(jlt.getJjdpk());

		SfZfQq qq = new SfZfQq();
		qq.setPk(TemplateUtil.genUUID());
		qq.setLrdwdm(user.getJgdm());
		qq.setLrdwmc(user.getJgmc());
		qq.setLrrxm(user.getXm());
		qq.setLrrjh(user.getJh());
		qq.setJjdpk(jlt.getJjdpk());
		qq.setReason("电信诈骗涉案账号");
		qq.setSubjecttype((short) 1);
		qq.setPaycode(jlt.getBankcode());
		qq.setPayname(jlt.getBankname());
		qq.setAccnumber(jlt.getCardnumber());
		qq.setStarttime(nowDate);
		qq.setExpiretime(TimeUtil.addDay(nowDate,2));
		qq.setTransferamount((long) 0);
		qq.setTransfertime(nowDate);

		bean.put("zhlx","支付账号");
		bean.put("zzje","0");
		bean.put("zzsj",TimeUtil.fmtDate(nowDate,null));
		bean.put("ajlb","电信诈骗");
		bean.put("zzfs","支付账号");
		bean.put("bankname",jlt.getBankname());
		bean.put("accountname",jlt.getAccountname());
		bean.put("cardnumber",jlt.getCardnumber());
		bean.put("shr",jjd!=null&&StringUtils.isNotBlank(jjd.getBarxm())?jjd.getBarxm():jlt.getAccountname());

		String mongoPk = znzfService.insertMongo("sf","zf",bean);

		qq.setFlws(mongoPk);
		this.insert(qq);

		//增加序列
		ZnzfQueue queue = new ZnzfQueue();
		queue.setSerpk(qq.getPk());
		queue.setSertype(QqlxEnum.sfQqlxZhifu.getKey());
		queue.setYxj((short) 2);
		queue.setJjdpk(jlt.getJjdpk());
		queue.setCardnumber(jlt.getCardnumber());
		queue.setLrdwdm(user.getJgdm());
		queue.setLrdwmc(user.getJgmc());
		queue.setLrrxm(user.getXm());
		queue.setLrrjh(user.getJh());
		queue.setBankcode(jlt.getBankcode());
		queue.setBankname(jlt.getBankname());
		znzfQueueService.insert(queue);

		result = qq.getPk();
		return result;
	}
}
